//
//  WakeupManager.m
//  yingzi_flutter_hairender
//
//  Created by 余镜周 on 2024/4/18.
//

#import "YZXfWakeupManager.h"

@interface YZXfWakeupManager ()<IFlyVoiceWakeuperDelegate>

@property (nonatomic, strong) IFlyVoiceWakeuper *iflyVoiceWakeuper;

@end

@implementation YZXfWakeupManager

+ (YZXfWakeupManager *)sharedManager {
    static YZXfWakeupManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [YZXfWakeupManager new];
    });
    return instance;
}

- (IFlyVoiceWakeuper *)iflyVoiceWakeuper {
    if (!_iflyVoiceWakeuper) {
        _iflyVoiceWakeuper = [IFlyVoiceWakeuper sharedInstance];
        _iflyVoiceWakeuper.delegate = self;
    }
    return _iflyVoiceWakeuper;
}

- (BOOL)isListening {
    return self.iflyVoiceWakeuper.isListening;
}

- (BOOL)start {
    if (self.isListening) {
        return true;
    }
    //设置唤醒门限值,新唤醒引擎的默认门限制值为1450
    //门限设置要和资源中的唤醒词个数匹配，以;分割。
    //例如：0:1450，0代表第一个唤醒词 1450，代表第一个唤醒词门限
    //根据下载的SDK中的说明来设置。
    //0：表示第一个唤醒词，1450表示唤醒词对应的门限值；
    //1：表示第二个唤醒词，1450表示唤醒词对应的门限值
    NSString *thresStr = [NSString stringWithFormat:@"0:%d", 1450];
    [self.iflyVoiceWakeuper setParameter:thresStr forKey:[IFlySpeechConstant IVW_THRESHOLD]];
    
    //设置唤醒的服务类型，目前仅支持wakeup
    [self.iflyVoiceWakeuper setParameter:@"wakeup" forKey:[IFlySpeechConstant IVW_SST]];
    
    //生成唤醒资源路径并设置唤醒资源，唤醒资源需要定制，与唤醒词一一对应。
    NSString *resPath = [[NSBundle mainBundle] resourcePath];
    //jet文件必须和AppID一一对应，否则无法正常使用
    NSString *wordPath = [[NSString alloc] initWithFormat:@"%@/Xunfei/resource/ivw/a327ed87.jet",resPath];
    NSString *ivwResourcePath = [IFlyResourceUtil generateResourcePath:wordPath];
    [self.iflyVoiceWakeuper setParameter:ivwResourcePath forKey:@"ivw_res_path"];
    
    //设置唤醒的工作模式
    //keep_alive表示一次唤醒成功后是否继续录音等待唤醒。1：表示继续；0：表示唤醒终止
    [self.iflyVoiceWakeuper setParameter:@"1" forKey:[IFlySpeechConstant KEEP_ALIVE]];
    
    //set audio source
    [self.iflyVoiceWakeuper setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
    //set the audio path saved by recorder
    [self.iflyVoiceWakeuper setParameter:@"ivw.pcm" forKey:@"ivw_audio_path"];
    
    //启动唤醒
    BOOL bRet = [self.iflyVoiceWakeuper startListening];
    
    return bRet;
}

- (BOOL)stop {
    return [self.iflyVoiceWakeuper stopListening];
}

#pragma mark - delegate
/*!
 * 录音开始
 */
- (void)onBeginOfSpeech {
    if ([_delegate respondsToSelector:@selector(onBeginOfSpeech)]) {
        [_delegate onBeginOfSpeech];
    }
}

/*!
 * 录音结束
 */
- (void)onEndOfSpeech {
    if ([_delegate respondsToSelector:@selector(onEndOfSpeech)]) {
        [_delegate onEndOfSpeech];
    }
}

/*!
 * 会话错误
 *
 * @param error 错误描述类，
 */
- (void)onCompleted:(IFlySpeechError *)error {
    if (error.errorCode!=0) {
        NSLog(@"%s,errorCode:%d, %@",__func__,error.errorCode, error.errorDesc);
    }
    if (error.errorCode==10102) {
        NSLog(@"%s,errorCode:%d, %@",__func__,error.errorCode, error.errorDesc);
    }
    
    if ([_delegate respondsToSelector:@selector(onCompleted:)]) {
        [_delegate onCompleted:error];
    }
}

/*!
 * 唤醒结果
 *
 * @param resultDic 唤醒结果字典
 */
//【KEYWORD】   xiao2-ying3-xiao2-ying3
//【SST】   wakeup
//【ID】    0
//【SCORE】 2075
//【EOS】   4460
//【BOS】   3530
- (void)onResult:(NSMutableDictionary *)resultDic {
//    NSString *sst = [resultDic objectForKey:@"sst"];
//    NSNumber *wakeId = [resultDic objectForKey:@"id"];
//    NSString *score = [resultDic objectForKey:@"score"];
//    NSString *bos = [resultDic objectForKey:@"bos"];
//    NSString *eos = [resultDic objectForKey:@"eos"];
    NSString *keyword = [resultDic objectForKey:@"keyword"];
    
//    NSLog(@"【KEYWORD】   %@",keyword);
//    NSLog(@"【SST】   %@",sst);
//    NSLog(@"【ID】    %@",wakeId);
//    NSLog(@"【SCORE】 %@",score);
//    NSLog(@"【EOS】   %@",eos);
//    NSLog(@"【BOS】   %@",bos);
//    
//    NSMutableString *result = [[NSMutableString alloc] init];
//    [result appendFormat:@"\n"];
//    [result appendFormat:@"【KEYWORD】        %@\n",keyword];
//    [result appendFormat:@"【SST】        %@\n",sst];
//    [result appendFormat:@"【ID】         %@\n",wakeId];
//    [result appendFormat:@"【SCORE】      %@\n",score];
//    [result appendFormat:@"【EOS】        %@\n",eos];
//    [result appendFormat:@"【BOS】        %@\n",bos];
    
    if ([_delegate respondsToSelector:@selector(onResult:)]) {
        [_delegate onResult:resultDic];
    }
}

/*!
 * 音量反馈，返回频率与录音数据返回回调频率一致
 *
 * @param volume 音量值
 */
- (void)onVolumeChanged:(int)volume {
//    NSString *vol = [NSString stringWithFormat:@"%@：%d", NSLocalizedString(@"T_RecVol", nil), volume];
//    NSLog(@"onVolumeChanged %@", vol);
    if ([_delegate respondsToSelector:@selector(onVolumeChanged:)]) {
        [_delegate onVolumeChanged:volume];
    }
}


@end
